import React, { useState } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Space,
  Typography,
  Row,
  Col,
  Alert,
  message,
  Steps,
} from 'antd';
import {
  TeamOutlined,
  CheckCircleOutlined,
  ArrowLeftOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { teamApi } from '../services/api';

const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;

interface CreateTeamForm {
  name: string;
  description?: string;
}

const TeamCreate: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [currentStep, setCurrentStep] = useState(0);
  const [formData, setFormData] = useState<CreateTeamForm>({ name: '', description: '' });

  // 处理表单提交
  const handleSubmit = async (values: CreateTeamForm) => {
    setLoading(true);
    try {
      const response = await teamApi.createTeam(values);

      message.success('团队创建成功！');

      // 跳转到团队详情页面
      if (response.id) {
        navigate(`/teams/${response.id}`);
      }
    } catch (error: any) {
      console.error('Create team failed:', error);
      message.error(error.response?.data?.error?.message || '创建团队失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理最终团队创建（使用存储的表单数据）
  const handleCreateTeam = async () => {
    setLoading(true);
    try {
      const response = await teamApi.createTeam(formData);

      message.success('团队创建成功！');

      // 跳转到团队详情页面
      if (response.id) {
        navigate(`/teams/${response.id}`);
      }
    } catch (error: any) {
      console.error('Create team failed:', error);
      message.error(error.response?.data?.error?.message || '创建团队失败');
    } finally {
      setLoading(false);
    }
  };

  // 步骤配置
  const steps = [
    {
      title: '基本信息',
      icon: <TeamOutlined />,
      description: '填写团队名称和描述',
    },
    {
      title: '确认创建',
      icon: <CheckCircleOutlined />,
      description: '检查信息并创建团队',
    },
  ];

  // 下一步
  const nextStep = () => {
    form.validateFields().then((values) => {
      setFormData(values);
      setCurrentStep(currentStep + 1);
    });
  };

  // 上一步
  const prevStep = () => {
    setCurrentStep(currentStep - 1);
  };

  // 获取表单值用于确认页面 - 使用formData状态
  const formValues = formData;

  return (
    <div style={{ maxWidth: 800, margin: '0 auto', padding: '24px' }}>
      {/* 页面标题 */}
      <Row justify="space-between" align="middle" style={{ marginBottom: '24px' }}>
        <Col>
          <Title level={2} style={{ margin: 0 }}>
            创建新团队
          </Title>
          <Text type="secondary">
            创建一个团队来协作管理遥测数据和分析工作
          </Text>
        </Col>
        <Col>
          <Button
            icon={<ArrowLeftOutlined />}
            onClick={() => navigate('/teams')}
          >
            返回团队列表
          </Button>
        </Col>
      </Row>

      {/* 步骤指示器 */}
      <Card style={{ marginBottom: '24px' }}>
        <Steps current={currentStep} size="small">
          {steps.map((step, index) => (
            <Steps.Step
              key={index}
              title={step.title}
              description={step.description}
              icon={step.icon}
            />
          ))}
        </Steps>
      </Card>

      <Card title="创建团队" bordered={false}>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{
            name: '',
            description: '',
          }}
        >
          {/* 第一步：基本信息 */}
          {currentStep === 0 && (
            <Space direction="vertical" size="large" style={{ width: '100%' }}>
              <Alert
                message="团队信息"
                description="请填写团队的基本信息，这些信息可以帮助成员了解团队的用途和目标。"
                type="info"
                showIcon
              />

              <Form.Item
                label="团队名称"
                name="name"
                rules={[
                  { required: true, message: '请输入团队名称' },
                  { min: 1, max: 100, message: '团队名称长度应在1-100个字符之间' },
                  {
                    pattern: /^[a-zA-Z0-9\u4e00-\u9fa5\s\-_]+$/,
                    message: '团队名称只能包含字母、数字、中文、空格、连字符和下划线',
                  },
                ]}
              >
                <Input
                  placeholder="请输入团队名称"
                  size="large"
                  showCount
                  maxLength={100}
                />
              </Form.Item>

              <Form.Item
                label="团队描述"
                name="description"
                rules={[
                  { max: 500, message: '描述长度不能超过500个字符' },
                ]}
              >
                <TextArea
                  placeholder="请简要描述团队的用途、目标或工作范围..."
                  rows={4}
                  showCount
                  maxLength={500}
                />
              </Form.Item>

              <Row justify="end">
                <Space>
                  <Button onClick={() => navigate('/teams')}>
                    取消
                  </Button>
                  <Button type="primary" onClick={nextStep}>
                    下一步
                  </Button>
                </Space>
              </Row>
            </Space>
          )}

          {/* 第二步：确认信息 */}
          {currentStep === 1 && (
            <Space direction="vertical" size="large" style={{ width: '100%' }}>
              <Alert
                message="请确认团队信息"
                description="请仔细检查以下信息，确认无误后点击创建团队。"
                type="warning"
                showIcon
              />

              <Card size="small" title="团队信息预览">
                <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                  <Row>
                    <Col span={4}>
                      <Text strong>团队名称：</Text>
                    </Col>
                    <Col span={20}>
                      <Text>{formValues?.name || '未填写'}</Text>
                    </Col>
                  </Row>
                  <Row>
                    <Col span={4}>
                      <Text strong>团队描述：</Text>
                    </Col>
                    <Col span={20}>
                      <Text>
                        {formValues?.description || '无描述'}
                      </Text>
                    </Col>
                  </Row>
                  <Row>
                    <Col span={4}>
                      <Text strong>创建者：</Text>
                    </Col>
                    <Col span={20}>
                      <Text>您将成为团队的所有者</Text>
                    </Col>
                  </Row>
                </Space>
              </Card>

              <Card size="small" title="创建后说明">
                <Paragraph>
                  <ul>
                    <li>您将成为该团队的<strong>所有者</strong>，拥有完整的管理权限</li>
                    <li>创建后您可以邀请成员加入团队</li>
                    <li>可以设置不同角色的成员权限</li>
                    <li>可以随时修改团队信息和成员设置</li>
                  </ul>
                </Paragraph>
              </Card>

              <Row justify="space-between">
                <Button onClick={prevStep} icon={<ArrowLeftOutlined />}>
                  上一步
                </Button>
                <Space>
                  <Button onClick={() => navigate('/teams')}>
                    取消
                  </Button>
                  <Button
                    type="primary"
                    onClick={handleCreateTeam}
                    loading={loading}
                    size="large"
                  >
                    创建团队
                  </Button>
                </Space>
              </Row>
            </Space>
          )}
        </Form>
      </Card>

      {/* 帮助信息 */}
      <Card title="团队角色说明" style={{ marginTop: '24px' }} size="small">
        <Row gutter={16}>
          <Col span={6}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', marginBottom: '8px' }}>👑</div>
              <div style={{ fontWeight: 600, marginBottom: '4px' }}>所有者</div>
              <div style={{ fontSize: '12px', color: '#666' }}>
                完整控制权限，可删除团队
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', marginBottom: '8px' }}>⚙️</div>
              <div style={{ fontWeight: 600, marginBottom: '4px' }}>管理员</div>
              <div style={{ fontSize: '12px', color: '#666' }}>
                管理成员和团队设置
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', marginBottom: '8px' }}>👤</div>
              <div style={{ fontWeight: 600, marginBottom: '4px' }}>成员</div>
              <div style={{ fontSize: '12px', color: '#666' }}>
                可创建提取和分析任务
              </div>
            </Card>
          </Col>
          <Col span={6}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '24px', marginBottom: '8px' }}>👁️</div>
              <div style={{ fontWeight: 600, marginBottom: '4px' }}>查看者</div>
              <div style={{ fontSize: '12px', color: '#666' }}>
                只能查看团队数据
              </div>
            </Card>
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export default TeamCreate;